//
//  NetworkHandle.m
//  UI19_网络封装(delegate回调)
//
//  Created by dllo on 16/1/7.
//  Copyright © 2016年 dilo. All rights reserved.
//

#import "NetworkHandle.h"
#import <AFNetworking.h>
#import <CommonCrypto/CommonDigest.h>
#import "Reachability.h"

@implementation NetworkHandle


/** 通过 NSURLSession 实现网络请求 */

- (void)networkHandleJSONWithURl:(NSString *) urlString {
    
    //  AFN 判读网络状态(有问题 此时刷新的数据读不出来)
    
    //    // 1.获得网络监控的管理者
    //    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    //
    //    // 2.设置网络状态改变后的处理
    //    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    //
    //        // 当网络状态改变了, 就会调用这个block
    //        switch (status) {
    //            case AFNetworkReachabilityStatusUnknown: // 未知网络
    //                NSLog(@"未知网络");
    //                break;
    //
    //            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
    //
    //
    //                NSLog(@"没有网络1(断网)");
    //
    //
    //                NSString *cook = @"cook/";
    //                NSString *behind = @".data";
    //                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //
    //                NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkHandle md5HexDigest:urlString],behind]];
    //
    //               // NSLog(@"%@", path);
    //                NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
    //
    //                NSError *errorJOSON = nil;
    //                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
    //
    //                if ([self.delegate respondsToSelector:@selector(handleDidComplete:)]) {
    //
    //                    [self.delegate  handleDidComplete:result];
    //                }
    //
    //                break;
    //
    //            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
    //
    //                NSLog(@"2g/3g4g网");
    //
    //                break;
    //
    //            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
    //
    //                NSLog(@"WIFI网络");
    //
    //           // 将字符串进行转码 (URL 中不能含有中文等字符 )
    //                //NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //
    //                // URL
    //                NSURL *url = [NSURL URLWithString:urlString];
    //                //NSURL *url = [NSURL URLWithString:temp];
    //
    //                // session
    //
    //                NSURLSession *session = [NSURLSession sharedSession];
    //                // add task
    //
    //                NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    //
    //                    dispatch_sync(dispatch_get_main_queue(), ^(){
    //
    //                        NSString *cook = @"cook/";
    //                        NSString *behind = @".data";
    //                        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //
    //                        NSString* path =[libPath stringByAppendingPathComponent:[cook stringByAppendingFormat:@"%@%@", [NetworkHandle md5HexDigest:urlString],behind]];
    //
    //                        [data writeToFile:path  atomically:YES];
    //
    //                        NSError *errorJOSON = nil;
    //                        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
    //
    //                        if ([self.delegate respondsToSelector:@selector(handleDidComplete:)]) {
    //
    //                            [self.delegate  handleDidComplete:result];
    //                        }
    //
    //                    });
    //
    //                }];
    //
    //                [task resume];
    //                break;
    //        }
    //
    //    }];
    //
    //    [mgr startMonitoring];
    //
    
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:{
            isExistenceNetwork = NO;
            NSLog(@"没网");
            break;
        }
        case ReachableViaWiFi:{
            isExistenceNetwork = YES;
            break;
        }
        case ReachableViaWWAN:{
            isExistenceNetwork = YES;
            break;
        }
    }
    if (isExistenceNetwork) {
        
        
        // 将字符串进行转码 (URL 中不能含有中文等字符 )
        //NSString *temp = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        // URL
        NSURL *url = [NSURL URLWithString:urlString];
        //NSURL *url = [NSURL URLWithString:temp];
        
        // session
        
        NSURLSession *session = [NSURLSession sharedSession];
        // add task
        
        NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            dispatch_sync(dispatch_get_main_queue(), ^(){
                
               // NSString *cook = @"cook/";
                NSString *behind = @".data";
                NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
                
                NSString* path =[libPath stringByAppendingPathComponent:[[NetworkHandle md5HexDigest:urlString] stringByAppendingFormat:@"%@", behind]];
             //   NSLog(@"%@", path);
                
                [data writeToFile:path  atomically:YES];
                
                NSError *errorJOSON = nil;
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
                
                if ([self.delegate respondsToSelector:@selector(handleDidComplete:)]) {
                    
                    [self.delegate  handleDidComplete:result];
                }
                
            });
            
        }];
        
        [task resume];
        
        
    }else {
        
        NSLog(@"没有网络(断网)");
        
       // NSString *cook = @"cook/";
        NSString *behind = @".data";
        NSString *libPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        
        NSString* path =[libPath stringByAppendingPathComponent:[[NetworkHandle md5HexDigest:urlString] stringByAppendingFormat:@"%@", behind]];
        
        // NSLog(@"%@", path);
        NSMutableData *data = [NSMutableData dataWithContentsOfFile:path];
        
     //   NSLog(@"%@", data);
        
        if (data == nil) {
            
            return;
            
        } else {
            
            NSError *errorJOSON = nil;
            id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJOSON];
            
            if ([self.delegate respondsToSelector:@selector(handleDidComplete:)]) {
                
                [self.delegate  handleDidComplete:result];
            }
        }
    }
}

+ (void)handlerJSONWitURL:(NSString *)urlstring delegate:(id<NetworkHandleDelegate>)delegateHandle {
    
    NetworkHandle *handler = [[NetworkHandle alloc] init];
    
    handler.delegate = delegateHandle;
    
    [handler networkHandleJSONWithURl:urlstring];
    
    [handler release];
    
}

/** md5加密 */
+ (NSString *)md5HexDigest:(NSString*)input {
    const char* str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (unsigned int)strlen(str), result);
    
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
    {
        [hash appendFormat:@"%02X", result[i]];
    }
    NSString *mdfiveString = [hash lowercaseString];
    
    return mdfiveString;
}


@end
